'use strict';

const Service = require('egg').Service;

class HomeService extends Service {
    async login() {
        const user = false;
        if (user) {
            this.ctx.cast(404, '用户不存在111111');
        }

        return 123;
    }

    /**
     * 注册流程
     * @param {*} param0
     */
    async register({ username, password, nickname }) {
        // 用户是否已注册
        const user = await this.service.user.findByEmail(username);
        if (user) {
            this.ctx.cast(403, '用户已注册');
        }
        // 生成 uuid
        const id = this.ctx.helper.uuid();
        const cid = this.ctx.helper.uuid();
        // 开启一个事务
        const conn = await this.app.mysql.beginTransaction();
        try {
            // 保存用户
            let sql = `
            insert into user 
                (id, email, password, nickname, cid, create_at)
            values
                (?, ?, ?, ?, ?, ?)
        `;
            await conn.query(sql, [
                id,
                username,
                this.ctx.helper.encrypt(password),
                nickname,
                cid,
                Date.now(),
            ]);

            // 保存专栏
            await conn.query(
                'insert into columns (id, title, pid, create_at) value (?, ?, ?, ?)',
                [id, `${nickname} 的专栏`, 'TB9E-uqnF-EWT0-wngK', Date.now()]
            );

            await conn.commit(); // 提交事务
        } catch (error) {
            // 回滚事务
            await conn.rollback(); // 一定记得捕获异常后回滚事务！！
            // 抛出异常
            this.ctx.cast('500', error.message);
        }
    }
}

module.exports = HomeService;
